const StringVar = require('./StringVar');

/**
 * @参数详情 obj 接收字符串的对象
 * @参数详情 key 接收字符串的键
 * @参数详情 allowNull 是否允许为空
 * @参数详情 allowOnlySpace 是否允许去除空白字符之后是空值
 * @参数详情 minLength 最小长度
 * @参数详情 maxLength 最大长度
 * @参数详情 delSpaceMinLength 去除空白字符之后最小长度
 * @参数详情 delSpaceMaxLength 去除空白字符之后最大长度
 */
class FormatSpaceString {
    constructor(obj, key, allowNull=false, allowOnlySpace=false, minLength = null, maxLength = null, delSpaceMinLength = null, delSpaceMaxLength = null) {
        this.obj = obj;
        this.key = key;
        this.allowNull = allowNull;
        this.allowOnlySpace = allowOnlySpace;
        this.minLength = minLength;
        this.maxLength = maxLength;
        this.delSpaceMinLength = delSpaceMinLength;
        this.delSpaceMaxLength = delSpaceMaxLength;
    }
    check() {
        let string = new StringVar(this.obj, this.key, this.allowNull, this.minLength, this.maxLength);
        let flag = string.check();
        if (!flag.success) {
            return flag;
        }
        this.OldValue = string.value;
        this.value = string.value;
        if (!this.allowOnlySpace) {
            // 去空白字符后判空
            let format_str = this.value.replace(/\s+/g, '');
            if (!format_str) {
                return { success: false, message: `${this.key} 不能只包含空白字符` };
            }
            // 长度判断
            if (this.delSpaceMinLength && format_str.length < this.delSpaceMinLength) {
                return { success: false, message: `${this.key} 长度不能小于 ${this.delSpaceMinLength}` };
            }
            if (this.delSpaceMaxLength && format_str.length > this.delSpaceMaxLength) {
                return { success: false, message: `${this.key} 长度不能大于 ${this.delSpaceMaxLength}` };
            }
            this.value = format_str;
        }
        return { success: true };
    }
}

module.exports = FormatSpaceString;